﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PowerPlan
{
    public partial class MainForm : Form
    {


        public MainForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 当前电源计划
        /// </summary>
        private static Powercfg currentPowercfg;
        /// <summary>
        /// 离开模式电源计划
        /// </summary>
        private static Powercfg leaveModePowercfg;
        /// <summary>
        /// 加速模式电源计划
        /// </summary>
        private static Powercfg speedupModePowercfg;
        /// <summary>
        /// 平衡模式电源计划
        /// </summary>
        private static Powercfg defaultModelPowercfg;
        /// <summary>
        /// CPU使用率阈值
        /// </summary>
        private static double cpuUsageThreshold = 50;
        /// <summary>
        /// 空闲切换超时时间，默认30s
        /// </summary>
        private static long idleTime = 30;
        /// <summary>
        /// 启用离开模式
        /// </summary>
        private static bool enableLeaveMode = false;
        /// <summary>
        /// 启用加速模式
        /// </summary>
        private static bool enableSpeedupMode = false;
        /// <summary>
        /// 关机计时方式
        /// </summary>
        private static string shutdownTiming = "键鼠空闲关机";
        /// <summary>
        /// 启用关机
        /// </summary>
        private static bool enableShutdown = false;
        /// <summary>
        /// 关机总倒计时秒
        /// </summary>
        private static int shutdownTotalSeconds = 0;
        /// <summary>
        /// 关机倒计时增加秒
        /// </summary>
        private static int shutdownUp = 0;
        /// <summary>
        /// 时间下拉选择列表B（60）
        /// </summary>
        private static object[] timeDropList = new object[61];
        /// <summary>
        /// 取消任务标记
        /// </summary>
        private static CancellationTokenSource tokenSource = new CancellationTokenSource();
        private static CancellationToken token;
        /// <summary>
        /// 窗口加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            token = tokenSource.Token;

            // 获取电源计划列表
            List<Powercfg> powercfgs = GetPowercfgList();
            string nn = "";
            for (int i = 0; i < powercfgs.Count; i++)
            {
                Powercfg cfg = powercfgs[i];
                //if (cfg.Name.Contains("AMD"))
                    //continue;
                nn += cfg.ToString() + " ";
                string name = cfg.Name;//.Replace("AMDRyzen?PowerSaver", "AMD节能").Replace("AMDRyzen?Balanced", "AMD平衡").Replace("AMDRyzen?HighPerformance", "AMD高性能");
                // 显示电源计划列表
                PowercfgList.Items.Add(name);
                // 离开模式选择列表
                LeaveModeValue.Items.Add(name);
                // 加速模式选择列表
                SpeedupModeValue.Items.Add(name);
                // 默认模式选择列表
                DefaultModelValue.Items.Add(name);
            }

            Log("电源计划列表初始化：" + nn);
            DefaultModelValue.SelectedItem = Computer.ReadValue("Power", "DefaultMode", "平衡");
            LeaveModeValue.SelectedItem = Computer.ReadValue("Power", "LeaveMode", "节能");
            SpeedupModeValue.SelectedItem = Computer.ReadValue("Power", "SpeedupMode", "高性能");
            if (IsNotFoundPowercfg(Computer.ReadValue("Power", "DefaultMode", "平衡")))
            {
                DefaultModelValue.SelectedItem = PowercfgList.Items[0];
            }
            if (IsNotFoundPowercfg(Computer.ReadValue("Power", "LeaveMode", "节能")))
            {
                LeaveModeValue.SelectedItem = PowercfgList.Items[0];
            }
            if (IsNotFoundPowercfg(Computer.ReadValue("Power", "SpeedupMode", "高性能")))
            {
                SpeedupModeValue.SelectedItem = PowercfgList.Items[0];
            }

            // 初始化CPU使用率阈值
            for (int i = 10; i < 90; i = i + 5)
            {
                CPUUsageValue.Items.Add(i + "");
            }
            cpuUsageThreshold = double.Parse(Computer.ReadValue("Power", "CPUUsageThreshold", "30"));
            CPUUsageValue.Text = cpuUsageThreshold + "";

            /*// 初始化加速模式开始和结束时间
            SpeedupModelStartTime.Value = DateTime.ParseExact(Computer.ReadValue("Power", "SpeedupModelBeginTime", "22:00:00"), "HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
            SpeedupModelEndTime.Value = DateTime.ParseExact(Computer.ReadValue("Power", "SpeedupModelEndTime", "08:00:00"), "HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
            Log("加速模式起始时间：" + SpeedupModelStartTime.Value.ToString("HH:mm:ss") + " - " + SpeedupModelEndTime.Value.ToString("HH:mm:ss"));*/

            LeaveMode.Checked = bool.Parse(Computer.ReadValue("Power", "EnableLeaveMode", "true"));
            SpeedupMode.Checked = bool.Parse(Computer.ReadValue("Power", "EnableSpeedupMode", "true"));

            // 下拉时间列表初始化
            for (int i = 0; i <= 60; i++)
            {
                timeDropList[i] = i;
            }
            // 初始化空闲超时时间选择列表
            for (int i = 10; i <= 300; i = i + 10)
            {
                if (i > 60)
                {
                    i = i + 50;
                }
                IdleTimeoutValue.Items.Add(i);

            }
            IdleTimeoutValue.SelectedItem = int.Parse(Computer.ReadValue("Power", "IdleTimeout", "30"));

            // 定时关机计时方式初始化
            TimingValue.Items.Add("键鼠空闲关机");
            TimingValue.Items.Add("倒计时关机");
            TimingValue.SelectedItem = Computer.ReadValue("Shutdown", "Timing", "键鼠空闲关机");

            //this.WindowState = FormWindowState.Minimized;

            // 启用线程代替Timer执行定时任务检测
            Task.Run(() => {
                long tempTimeSeconds = 0;
                while (!token.IsCancellationRequested)
                {
                    double cpuUsage = Computer.GetCPUTotalUsage();

                    long idleTimeSeconds = Computer.GetIdleTimeSeconds();
                    // 鼠标、键盘空闲时间超过设定时间
                    if (idleTimeSeconds > idleTime)
                    {
                        tempTimeSeconds = idleTimeSeconds - idleTime;
                        // 离开模式已启用
                        if (enableLeaveMode && !currentPowercfg.Equals(leaveModePowercfg))
                        {
                            // 判断当前时间是否是加速模式
                            if (cpuUsage > cpuUsageThreshold)
                            {
                                Log("CPU使用率过高，暂缓切换电源计划。CPU使用率：" + cpuUsage);
                            }
                            else
                            {
                                currentPowercfg = leaveModePowercfg;
                                ChangePowerPlan(currentPowercfg);
                                Log("鼠标键盘已空闲：" + idleTimeSeconds + "秒");
                                Log("电源计划切换为：" + currentPowercfg.ToString());
                            }
                        }
                    }
                    else
                    {                        
                        // 判断当前时间是否是加速模式
                        if (cpuUsage > cpuUsageThreshold)
                        {
                            // 加速模式已启用
                            if (enableSpeedupMode && !currentPowercfg.Equals(speedupModePowercfg))
                            {
                                currentPowercfg = speedupModePowercfg;
                                ChangePowerPlan(currentPowercfg);
                                Log("鼠标键盘已空闲：" + idleTimeSeconds + "秒");
                                Log("电源计划切换为：" + currentPowercfg.ToString());
                            }
                        }
                        // 切换为默认模式
                        else if (!currentPowercfg.Equals(defaultModelPowercfg))
                        {
                            Log("保持" + currentPowercfg.Name + "模式电源计划" + tempTimeSeconds + "秒");
                            currentPowercfg = defaultModelPowercfg;
                            ChangePowerPlan(currentPowercfg);
                            Log("电源计划还原为：" + currentPowercfg.ToString());
                            tempTimeSeconds = 0;
                        }
                    }
                    // 启用关机计划逻辑
                    if (enableShutdown)
                    {
                        shutdownUp++;
                        Invoke(new MethodInvoker(() =>
                        {
                            ShutdownRemainingTime.Text = "剩余时间：" + (shutdownTotalSeconds - shutdownUp) + "秒";
                        }));
                        if ("键鼠空闲关机".Equals(shutdownTiming))
                        {
                            Invoke(new MethodInvoker(() =>
                            {
                                ShutdownRemainingTime.Text = "剩余时间：" + (shutdownTotalSeconds - idleTimeSeconds) + "秒";
                            }));
                            if (idleTimeSeconds > shutdownTotalSeconds)
                            {
                                Computer.RunCmd("shutdown -s -t 10");
                                Log("鼠标键盘已空闲：" + idleTimeSeconds + "秒");
                                Log("执行关机指令并延迟10秒关机");
                            }
                        }
                    }
                    else
                    {

                        if (shutdownUp != 0)
                        {
                            shutdownUp = 0;
                            Invoke(new MethodInvoker(() =>
                            {
                                ShutdownRemainingTime.Text = "剩余时间：00秒";
                            }));
                        }
                    }
                    // 键鼠已空闲时间显示
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        FreeTimeShow.Text = String.Format("键鼠空闲：{0}秒", idleTimeSeconds);

                        CPUUsage.Text = String.Format("CPU使用率：{0}%", cpuUsage.ToString("0.00"));
                    }));
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
            }, token);

            ThreadPool.RegisterWaitForSingleObject(Program.Started, (state, timeout) =>
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.Show();
                    // 注意：一定要在窗体显示后，再对属性进行设置
                    this.WindowState = FormWindowState.Normal;
                }));
            }, null, -1, false);

            // 启动最小化检测
            bool launchToTrayIcon = bool.Parse(Computer.ReadValue("App", "LaunchToTrayIcon", "True"));
            if (launchToTrayIcon)
            {
                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                // 显示托盘图标
                this.PowerPlanNotify.Visible = true;
                // 隐藏当前窗口
                this.Hide();
            }
        }

        

        /// <summary>
        /// 获取电源计划配置列表
        /// </summary>
        /// <returns>List<Dictionary<string, string>></returns>
        private List<Powercfg> GetPowercfgList()
        {
            string powercfgStr = Computer.RunCmd("powercfg /l");
            Console.WriteLine(powercfgStr);
            powercfgStr = powercfgStr.Substring(powercfgStr.IndexOf("电源方案 GUID: "));
            Console.WriteLine(powercfgStr);

            powercfgStr = powercfgStr.Replace("电源方案 GUID", "");
            Console.WriteLine(powercfgStr);
            string[] powercfgArray = powercfgStr.Split(":".ToCharArray());
            List<Powercfg> list = new List<Powercfg>();
            foreach (string powercfgInfo in powercfgArray)
            {
                if (!string.IsNullOrEmpty(powercfgInfo))
                {
                    string powercfgInfo1 = powercfgInfo.Replace(" ", "").Replace("\r\n", "");
                    Console.WriteLine(powercfgInfo1);
                    string powercfgUUID = powercfgInfo1.Substring(0, powercfgInfo1.IndexOf("("));
                    string powercfgName = powercfgInfo1.Substring(powercfgInfo1.IndexOf("("));
                    powercfgName = powercfgName.Substring(0, powercfgName.IndexOf(")")).Replace("(", "");
                    Powercfg powercfg = new Powercfg();
                    powercfg.UUID = powercfgUUID;
                    powercfg.Name = powercfgName;
                    list.Add(powercfg);
                }
            }
            return list;
        }

        /// <summary>
        /// 双击列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PowercfgList_DoubleClick(object sender, EventArgs e)
        {
            ListBox powercfgList = (ListBox)sender;
            string name = powercfgList.SelectedItem + "";
            Console.WriteLine(name);
            Powercfg cfg = GetPowercfg(name);
            if (cfg != null)
            {
                currentPowercfg = defaultModelPowercfg = cfg;
                DefaultModelValue.SelectedItem = cfg.Name;
                Log("默认电源计划设置为：" + cfg);
                ChangePowerPlan(cfg);
                this.PowerPlanNotify.ShowBalloonTip(2000, "电源计划", "电源计划修改为：“" + cfg.Name + "”", ToolTipIcon.Info);
            }
        }

        /// <summary>
        /// 通过name匹配Powercfg
        /// </summary>
        /// <param name="powercfgName">显示名称</param>
        /// <returns>Powercfg</returns>
        private Powercfg GetPowercfg(string powercfgName)
        {
            List<Powercfg> powercfgs = GetPowercfgList();
            foreach (Powercfg cfg in powercfgs)
            {
                if (cfg.Name.Equals(powercfgName))
                {
                    return cfg;
                }
            }
            return null;
        }

        /// <summary>
        /// 电源计划不存在
        /// </summary>
        /// <param name="powercfgName">电源计划名称</param>
        /// <returns></returns>
        private bool IsNotFoundPowercfg(string powercfgName)
        {
            return GetPowercfg(powercfgName) == null;
        }

        /// <summary>
        /// 离开模式选定结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LeaveModeValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox leaveModeComboBox = (ComboBox)sender;
            Console.WriteLine(leaveModeComboBox.SelectedItem);
            leaveModePowercfg = GetPowercfg(leaveModeComboBox.SelectedItem + "");
            Log("离开模式电源计划设置为：" + leaveModePowercfg.ToString());
            Computer.WriteValue("Power", "LeaveMode", leaveModePowercfg.ToString());
        }

        /// <summary>
        /// 加速模式选定结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SpeedupModeValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox nightModeComboBox = (ComboBox)sender;
            Console.WriteLine(nightModeComboBox.SelectedItem);
            speedupModePowercfg = GetPowercfg(nightModeComboBox.SelectedItem + "");
            Log("加速模式电源计划设置为：" + speedupModePowercfg.ToString());
            Computer.WriteValue("Power", "SpeedupMode", speedupModePowercfg.ToString());
        }

        /// <summary>
        /// 日志输出
        /// </summary>
        /// <param name="log"></param>
        private void Log(string log)
        {
            Invoke(new MethodInvoker(() =>
            {
                logBox.AppendText(DateTime.Now.ToString() + " - " + log + "\r\n");
            }));
        }

        /// <summary>
        /// 离开模式启用状态切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LeaveMode_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox leaveModeCheckBox = (CheckBox)sender;
            enableLeaveMode = leaveModeCheckBox.Checked;
            Log((enableLeaveMode ? "启用" : "停用") + "离开模式电源计划（" + enableLeaveMode + "）");
            Computer.WriteValue("Power", "EnableLeaveMode", enableLeaveMode);
        }

        /// <summary>
        /// 加速模式启用状态切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SpeedupMode_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox nightModeCheckBox = (CheckBox)sender;
            enableSpeedupMode = nightModeCheckBox.Checked;
            Log((enableSpeedupMode ? "启用" : "停用") + "加速模式电源计划（" + enableSpeedupMode + "）");
            Computer.WriteValue("Power", "EnableSpeedupMode", enableSpeedupMode);
        }

        /// <summary>
        /// 空闲切换超时时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IdleTimeoutValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox IdleTimeoutComboBox = (ComboBox)sender;
            idleTime = long.Parse(IdleTimeoutComboBox.SelectedItem + "");
            Log("电源计划切换超时时间：" + idleTime + "秒");
            Computer.WriteValue("Power", "IdleTimeout", idleTime);
        }

        /// <summary>
        /// 默认模式选定结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DefaultModelValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox defaultModeComboBox = (ComboBox)sender;
            Console.WriteLine(defaultModeComboBox.SelectedItem);
            PowercfgList.SelectedItem = defaultModeComboBox.SelectedItem;
            currentPowercfg = defaultModelPowercfg = GetPowercfg(defaultModeComboBox.SelectedItem + "");
            Log("默认模式电源计划设置为：" + defaultModelPowercfg.ToString());
            Computer.WriteValue("Power", "DefaultMode", defaultModelPowercfg.ToString());
        }

       /// <summary>
       /// CPU使用率阈值选中
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>

        private void CPUUsageValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cpuUsageValueComboBox = (ComboBox)sender;
            Console.WriteLine(cpuUsageValueComboBox.SelectedItem);
            Log("CPU使用率阈值为：" + cpuUsageValueComboBox.SelectedItem);

            Computer.WriteValue("Power", "CPUUsageThreshold", cpuUsageValueComboBox.SelectedItem);
        }

        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true;
                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                // 显示托盘图标
                this.PowerPlanNotify.Visible = true;
                // 隐藏当前窗口
                this.Hide();
                return;
            }
            // 系统关闭 || 任务管理器关闭 || 程序退出
            else if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.TaskManagerClosing || e.CloseReason == CloseReason.ApplicationExitCall)
            {
                tokenSource.Cancel();
            }
        }

        /// <summary>
        /// 双击托盘图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PowerPlanNotify_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Focus();
            }
        }

        /// <summary>
        /// 退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.PowerPlanNotify.Visible = false;
            this.PowerPlanNotify.Dispose();
            // 关闭所有的线程
            this.Dispose();
            this.Close();
            Environment.Exit(Environment.ExitCode);
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            logBox.Text = "";
        }

        /// <summary>
        /// 修改电源计划
        /// </summary>
        /// <param name="powercfg"></param>
        private void ChangePowerPlan(Powercfg powercfg)
        {
            Computer.RunCmd("powercfg -setactive " + powercfg.UUID);
        }

        /// <summary>
        /// 计时方式值选定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimingValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox timingValueComboBox = (ComboBox)sender;
            shutdownTiming = timingValueComboBox.SelectedItem + "";
            Log("关机计划计时方式：" + shutdownTiming);
            Computer.WriteValue("Shutdown", "Timing", shutdownTiming);
            // 清空下拉框
            ShutdownHourValue.Items.Clear();
            ShutdownMinuteValue.Items.Clear();
            ShutdownSecondValue.Items.Clear();
            // 根据选定类型切换时间设定
            switch (shutdownTiming)
            {
                case "倒计时关机":
                    ShutdownHourValue.Items.AddRange(timeDropList);
                    ShutdownMinuteValue.Items.AddRange(timeDropList);
                    ShutdownSecondValue.Items.AddRange(timeDropList);

                    ShutdownHourValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "CountdownShutdownTimeHour", "00"));
                    ShutdownMinuteValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "CountdownShutdownTimeMinute", "30"));
                    ShutdownSecondValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "CountdownShutdownTimeSecond", "00"));
                    Log("倒计时关机时间为：" + GetTime(ShutdownHourValue.SelectedItem, ShutdownMinuteValue.SelectedItem, ShutdownSecondValue.SelectedItem) + "（倒计时）=> 设定时间为倒计时");
                    break;
                case "键鼠空闲关机":
                    ShutdownHourValue.Items.AddRange(timeDropList);
                    ShutdownMinuteValue.Items.AddRange(timeDropList);
                    ShutdownSecondValue.Items.AddRange(timeDropList);

                    ShutdownHourValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "IdleShutdownTimeHour", "00"));
                    ShutdownMinuteValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "IdleShutdownTimeMinute", "10"));
                    ShutdownSecondValue.SelectedItem = int.Parse(Computer.ReadValue("Shutdown", "IdleShutdownTimeSecond", "00"));
                    Log("键鼠空闲关机时间为：" + GetTime(ShutdownHourValue.SelectedItem, ShutdownMinuteValue.SelectedItem, ShutdownSecondValue.SelectedItem) + "（键鼠空闲）=> 设定时间为键鼠空闲超时");
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 关机时间定时任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonShutdown_Click(object sender, EventArgs e)
        {
            if (enableShutdown)
            {
                enableShutdown = false;
                ButtonShutdown.Text = "开始";
                Log("停止" + shutdownTiming);
                Computer.RunCmd("shutdown -a");
            }
            else
            {
                enableShutdown = true;
                ButtonShutdown.Text = "停止";
                Log("开始" + shutdownTiming);
                shutdownTotalSeconds = 0;
                int h = int.Parse(ShutdownHourValue.SelectedItem + "");
                int m = int.Parse(ShutdownMinuteValue.SelectedItem + "");
                int s = int.Parse(ShutdownSecondValue.SelectedItem + "");
                if (h > 0)
                {
                    shutdownTotalSeconds += h * 60 * 60;
                }
                if (m > 0)
                {
                    shutdownTotalSeconds += m * 60;
                }
                if (s > 0)
                {
                    shutdownTotalSeconds += s;
                }
                Computer.RunCmd("shutdown -a");
                if ("倒计时关机".Equals(shutdownTiming))
                {
                    shutdownTotalSeconds++;
                    if (shutdownTotalSeconds > 0)
                    {
                        Computer.RunCmd("shutdown -s -t " + shutdownTotalSeconds);
                    }
                    else
                    {
                        Computer.RunCmd("shutdown -s -t 0");
                    }
                }
            }
        }

        /// <summary>
        /// 获取友好显示时间
        /// </summary>
        /// <returns></returns>
        private string GetTime(object hour, object minute, object second, bool amity = false)
        {
            string h = hour + "";
            if (h.Length < 2)
            {
                h = "0" + h;
            }
            string m = minute + "";
            if (m.Length < 2)
            {
                m = "0" + m;
            }
            string s = second + "";
            if (s.Length < 2)
            {
                s = "0" + s;
            }
            if (amity)
            {
                return string.Format("{0}:{1}:{2}", h, m, s);
            }
            return string.Format("{0}时{1}分{2}秒", h, m, s);
        }

        /// <summary>
        /// 时选定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShutdownHourValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowShutdownText(ShutdownHourValue.SelectedItem, ShutdownMinuteValue.SelectedItem, ShutdownSecondValue.SelectedItem);
            if (TimingValue.SelectedItem.Equals("键鼠空闲关机"))
            {
                Computer.WriteValue("Shutdown", "IdleShutdownTimeHour", ShutdownHourValue.SelectedItem);
                
            }
            else
            {
                Computer.WriteValue("Shutdown", "CountdownShutdownTimeHour", ShutdownHourValue.SelectedItem);
            }
        }

        /// <summary>
        /// 分选定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShutdownMinuteValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowShutdownText(ShutdownHourValue.SelectedItem, ShutdownMinuteValue.SelectedItem, ShutdownSecondValue.SelectedItem);
            if (TimingValue.SelectedItem.Equals("键鼠空闲关机"))
            {
                Computer.WriteValue("Shutdown", "IdleShutdownTimeMinute", ShutdownMinuteValue.SelectedItem);

            }
            else
            {
                Computer.WriteValue("Shutdown", "CountdownShutdownTimeMinute", ShutdownMinuteValue.SelectedItem);
            }
        }

        /// <summary>
        /// 秒选定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShutdownSecondValue_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowShutdownText(ShutdownHourValue.SelectedItem, ShutdownMinuteValue.SelectedItem, ShutdownSecondValue.SelectedItem);
            if (TimingValue.SelectedItem.Equals("键鼠空闲关机"))
            {
                Computer.WriteValue("Shutdown", "IdleShutdownTimeSecond", ShutdownSecondValue.SelectedItem);

            }
            else
            {
                Computer.WriteValue("Shutdown", "CountdownShutdownTimeSecond", ShutdownSecondValue.SelectedItem);
            }
        }

        /// <summary>
        /// 按钮显示文字
        /// </summary>
        /// <param name="hour"></param>
        /// <param name="minute"></param>
        /// <param name="second"></param>
        private void ShowShutdownText(object hour, object minute, object second)
        {
            // 根据选定类型切换时间设定
            switch (shutdownTiming)
            {
                case "倒计时关机":
                    ShutdownPresupposeTime.Text = "倒计时关机：" + GetTime(hour, minute, second);
                    break;
                case "键鼠空闲关机":
                    ShutdownPresupposeTime.Text = "键鼠空闲关机：" + GetTime(hour, minute, second);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 启动后最小化显示或默认屏幕居中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 启动最小化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool launchToTrayIcon = bool.Parse(Computer.ReadValue("App", "LaunchToTrayIcon", "True"));
            if (!launchToTrayIcon)
            {
                Computer.WriteValue("App", "LaunchToTrayIcon", "True");
                Log("启用启动最小化");
            }
            else
            {
                Computer.WriteValue("App", "LaunchToTrayIcon", "False");
                Log("关闭启动最小化");
            }
        }
    }
}
